using Godot;
using System;

public partial class AudioManager : Node2D
{
    // int busIndex = 0;
    // void ChangeVolume(float value)
    // {
    //     if (value <= 0)
    //     {
    //         AudioServer.SetBusMute(busIndex, true);
    //         return;
    //     }

    //     if (AudioServer.IsBusMute(busIndex))
    //     {
    //         AudioServer.SetBusMute(busIndex, false);
    //     }

    //     AudioServer.SetBusVolumeDb(busIndex, ConvertPercentageToVolume(value));
    // }

    // float scale = 20f;
    // float divisor = 50f;
    // float ConvertPercentageToVolume(float percentage)
    // {
    //     return scale * (float)Math.Log10(percentage / divisor);
    // }

    static AudioStreamPlayer audioBgm;
    static AudioStreamPlayer audioEffect;

    public override void _Ready()
    {
        audioBgm = new AudioStreamPlayer();
        AddChild(audioBgm);
        audioBgm.Name = "AudioBgm";
        audioBgm.Bus = AudioServer.GetBusName(1);
        audioEffect = new AudioStreamPlayer();
        AddChild(audioEffect);
        audioEffect.Name = "AudioEffect";
        audioEffect.Bus = AudioServer.GetBusName(2);
    }

    public static void PlayBgm(AudioStream audioStream)
    {
        audioBgm.Stream = audioStream;
        audioBgm.Play();
    }
    static string lastBgmKey = "";
    public static void PlayBgm(string key)
    {
        if (key == lastBgmKey && !audioBgm.Playing)
        {
            audioBgm.Play();
        }
        else
        {
            lastBgmKey = key;
            audioBgm.Stop();
            audioBgm.Stream = GameUtil.GetAudioStream(key);
            audioBgm.Play();
        }
    }

    public static void PlayEffect(AudioStream audioStream)
    {
        audioEffect.Stream = audioStream;
        audioEffect.Play();
    }
    public static void PlayEffect(string key)
    {
        audioEffect.Stream = GameUtil.GetAudioStream(key);
        audioEffect.Play();
    }

    internal static void PauseBgm()
    {
        audioBgm.Stop();
    }

}
